package com.ble;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.ble.bean.CmdEntity;
import com.ble.fragment.SettingFragment;
import com.ble.fragment.StatusFragment;
import com.ble.fragment.WaveFormFragment;
import com.ble.utlis.CmdUtlis;
import com.ble.utlis.Global;
import com.ble.utlis.PreferenceUtil;
import com.ble.utlis.TextTools;
import com.ble.utlis.ToastUtil;
import com.ble.weight.MyAlertDialog;
import com.inuker.bluetooth.library.Constants;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleUnnotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.model.BleGattService;


import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import javax.security.auth.login.LoginException;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import static com.inuker.bluetooth.library.Code.REQUEST_SUCCESS;

public class BleDetailActivity extends AppCompatActivity {


    private String mac;
    private String NAME;
    private UUID serviceUUID;
    private UUID sendUUID;
    private ProgressDialog progressDialog;
    private UUID readUUID;

    String TAG = "TAG";
    private StatusFragment statusFragment;
    private SettingFragment settingFragment;
    private WaveFormFragment waveFormFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bledetail);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true); // 决定左上角图标的右侧是否有向左的小箭头, true

        init();
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //通过getMenuInflater()方法获得MenuInflate对象，通过MenuInflate对象的inflate方法创建活动菜单
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:// 点击返回图标事件
                exit();
                break;
            case R.id.switch1:
                setting();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }


    private void setting() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String adress = PreferenceUtil.getInstance(this).getAdress("01");
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_alert, null);
        final EditText editText = inflate.findViewById(R.id.et_adress);
        editText.setText(adress);
        builder.setView(inflate).setTitle("设置从机地址").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String s = editText.getText().toString();
                if (s.isEmpty()) {
                    Toast.makeText(BleDetailActivity.this, "设置失败！！地址不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (s.length() == 1) {
                    s = "0" + s;
                }

                PreferenceUtil.getInstance(BleDetailActivity.this).setAdress(s);
                Toast.makeText(BleDetailActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
                CmdUtlis.slaveAddress = (byte) Integer.parseInt(s);
            }
        }).setNeutralButton("取消", null).show();
    }

    private void exit() {
        MyAlertDialog myDialog = new MyAlertDialog(this).builder();
        myDialog.setGone().setTitle(getString(R.string.Tips))
                .setMsg(getString(R.string.exit_tips))
                .setNegativeButton(getString(R.string.cancel), null)
                .setPositiveButton(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        App.getBle().disconnect(mac);
                        finish();
                    }
                }).show();
    }

    private List<Fragment> fragmentList;

    private FragmentManager manager;
    private boolean settingFalg = false;
    int indexfalg = 0;

    private void initView() {
        fragmentList = new ArrayList<>();
        statusFragment = new StatusFragment();
        settingFragment = new SettingFragment();
        waveFormFragment = new WaveFormFragment();
        fragmentList.add(statusFragment);
        fragmentList.add(settingFragment);
        fragmentList.add(waveFormFragment);
        final RadioGroup rg_tab = findViewById(R.id.rg_tab);
        rg_tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                manager = getSupportFragmentManager();
                switch (checkedId) {
                    case R.id.rb_sszt:
                        indexfalg = 0;
                        getSupportActionBar().setTitle("实时状态");
                        if (fragmentList.get(0).isAdded()) {
                            manager.beginTransaction()
                                    .hide(fragmentList.get(1))
                                    .hide(fragmentList.get(2))
                                    .show(fragmentList.get(0))
                                    .commit();

                        } else {
                            manager.beginTransaction()
                                    .hide(fragmentList.get(1))
                                    .hide(fragmentList.get(2))
                                    .add(R.id.fl, fragmentList.get(0))
                                    .show(fragmentList.get(0))
                                    .commit();
                        }
                        break;
                    case R.id.rb_cs:
                        if (settingFalg) {
                            indexfalg = 1;
                            fragmentStart();
                            break;
                        }
                        AlertDialog.Builder builder = new AlertDialog.Builder(BleDetailActivity.this);
                        View inflate = LayoutInflater.from(BleDetailActivity.this).inflate(R.layout.dialog_alert, null);
                        final EditText editText = inflate.findViewById(R.id.et_adress);
                        editText.setMaxLines(8);
                        builder.setView(inflate).setTitle("请输入设置密码").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String s = editText.getText().toString();
                                if (s.isEmpty()) {
                                    Toast.makeText(BleDetailActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                                    rg_tab.getChildAt(0).performClick();
                                    return;
                                }

                                if(s.equals(systempw)){
                                    fragmentStart();
                                    settingFalg = true;
                                    indexfalg = 1;
                                }else{
                                    ToastUtil.showShort(BleDetailActivity.this,"密码错误");
                                    rg_tab.getChildAt(0).performClick();
                                }
                            }
                        }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                rg_tab.getChildAt(0).performClick();
                            }
                        }).show();
                        break;
                    case R.id.rb_bx:
                            indexfalg = 2;
                            fragmentStart1();

                }
            }
        });
        rg_tab.getChildAt(0).performClick();
       initDictionaries();
//
//
//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//
//                BleDetailActivity.this.runOnUiThread(() -> {
//
//                    GlobalIndex=7;
//                    handle(TextTools.hexString2Bytes("0106000304007B0A"));
//                }
//                );
//
//            }
//        },1300,100);
    }

    private void fragmentStart() {
        getSupportActionBar().setTitle("参数设置");
        if (fragmentList.get(1).isAdded()) {
            manager.beginTransaction()
                    .hide(fragmentList.get(0))
                    .hide(fragmentList.get(2))
                    .show(fragmentList.get(1))
                    .commit();
        } else {
            manager.beginTransaction()
                    .hide(fragmentList.get(0))
                    .hide(fragmentList.get(2))
                    .show(fragmentList.get(1))
                    .add(R.id.fl, fragmentList.get(1)).commit();
        }
    }

    private void fragmentStart1() {
        getSupportActionBar().setTitle("波形显示");
        if (fragmentList.get(2).isAdded()) {
            manager.beginTransaction()
                    .hide(fragmentList.get(0))
                    .hide(fragmentList.get(1))
                    .show(fragmentList.get(2))
                    .commit();
        } else {
            manager.beginTransaction()
                    .hide(fragmentList.get(0))
                    .hide(fragmentList.get(1))
                    .show(fragmentList.get(2))
                    .add(R.id.fl, fragmentList.get(2)).commit();
        }
    }


    protected void init() {
        String adress = PreferenceUtil.getInstance(this).getAdress("01");
        CmdUtlis.slaveAddress = (byte) Integer.parseInt(adress);
        mac = getIntent().getStringExtra("MAC");
        NAME = getIntent().getStringExtra("NAME");
        showpg("正在加载");
        initBle();

    }


    private void showpg(final String title) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(BleDetailActivity.this);
                    progressDialog.setMessage(title);
                    //设置点击屏幕不消失
                    progressDialog.setCanceledOnTouchOutside(false);
                    //设置点击返回键不消失
                    progressDialog.setCancelable(false);
                    progressDialog.show();
                } else {
                    progressDialog.setMessage(title);
                }
            }
        });

    }

    private void dismisspg() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            }
        });
    }

    String userpw=UUID.randomUUID().toString();
    String systempw=UUID.randomUUID().toString();

    public String getUserpw() {
        return userpw;
    }

    public void setUserpw(String userpw) {
        this.userpw = userpw;
    }

    public String getSystempw() {
        return systempw;
    }

    public void setSystempw(String systempw) {
        this.systempw = systempw;
    }

    private void initBle() {
        int status = App.getBle().getConnectStatus(mac);

        if (status == Constants.STATUS_DEVICE_CONNECTING || status == Constants.STATUS_DEVICE_CONNECTED) {
            BleGattProfile bleGattProfile = Global.bleGattProfileMap.get(mac);
            getMessage(bleGattProfile);
            dismisspg();
        } else {
            BleConnectOptions options = new BleConnectOptions.Builder()
                    .setConnectRetry(3)   // 连接如果失败重试3次
                    .setConnectTimeout(30000)   // 连接超时30s
                    .setServiceDiscoverRetry(3)  // 发现服务如果失败重试3次
                    .setServiceDiscoverTimeout(20000)  // 发现服务超时20s
                    .build();
            Log.e(TAG, "initBle: 开始连接");
            App.getBle().connect(mac, options, new BleConnectResponse() {
                @Override
                public void onResponse(int code, BleGattProfile data) {
                    if (code != REQUEST_SUCCESS) {
                        finish();
                        return;
                    }

                    getMessage(data);
                    Global.bleGattProfileMap.put(mac, data);
                    dismisspg();
                }
            });
        }
    }

    private void getMessage(BleGattProfile data) {
        BleGattService service = data.getService(UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"));
        if (service == null) {
            Toast.makeText(this, "service 获取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        serviceUUID = service.getUUID();
        sendUUID = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
        readUUID = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
        App.getBle().notify(mac, service.getUUID(), readUUID, bleNotifyResponse);
        App.getBle().registerConnectStatusListener(mac, bleConnectStatusListener);
    }

    byte[] time=new byte[4];

    Map<Integer, String> ssz = new HashMap<>();

    public Map<Integer, String> getSsz() {
        return ssz;
    }

    private void handle(byte[] data) {
        statusFragment.addMsg(TextTools.byteToHexString(data));
        Log.e(TAG, "handle: " + TextTools.byteToHexString(data) + "   GlobalIndex:" + GlobalIndex);
        if (indexfalg == 1) {
            settinghandle(data);
            return;
        }

        try {
            CmdEntity data1 = CmdUtlis.getData(data);

            int type = data1.getType();

            if(type!=1&&type!=3){
                return;
            }


            byte[] bydata = data1.getBydata();
            if(bydata==null||bydata.length==0){
                return;
            }
//            if (GlobalIndex == 0) {
//                byte datum0 = bydata[0];
//                byte datum1 = bydata[1];
//                int t00001 = TextTools.getBits(datum0, 0, 1);
//                statusFragment.setValue(00001, t00001 > 0 ? "ON" : "OFF", null);
//                int t00002 = TextTools.getBits(datum0, 1, 1);
//                statusFragment.setValue(00002, t00002 > 0 ? "ON" : "OFF", null);
//                int t00010 = TextTools.getBits(datum1, 1, 1);
//                statusFragment.setValue(00010, t00010 > 0 ? "ON" : "OFF", null);
//            }

            if (GlobalIndex == 0) {
                Log.e("40001", "handle: " + TextTools.byteToHexString(bydata));
                int index = 40001;
                for (int i = 0; i < bydata.length; i += 2) {
                    byte[] bytes = new byte[2];
                    System.arraycopy(bydata, i, bytes, 0, bytes.length);
                    int a = TextTools.byteToInt2New(bytes);
                    statusFragment.setValue(index, String.valueOf(a), bytes);
                    settingFragment.setValue(index, String.valueOf(a), bytes,null);
                    ssz.put(index, String.valueOf(a));
                    waveFormFragment.setValue(index, String.valueOf(a), bytes);
                    if(index==40025){
                        time[0]=bytes[0];
                        time[1]=bytes[1];
                    }
                    if(index==40026){
                        time[2]=bytes[0];
                        time[3]=bytes[1];
                        statusFragment.setValue(4002526,String.valueOf(ByteBuffer.wrap(time).getInt()), bytes);
                    }

                    if(index==40029){
                        byte datum0 = bytes[0];
                        byte datum1 = bytes[1];
                        int t00001 = TextTools.getBits(datum1, 0, 1);
                        statusFragment.setValue(00001, t00001 > 0 ? "ON" : "OFF", null);
                        int t00002 = TextTools.getBits(datum1, 1, 1);
                        statusFragment.setValue(00002, t00002 > 0 ? "ON" : "OFF", null);
                        int t00010 = TextTools.getBits(datum0, 1, 1);
                        statusFragment.setValue(00010, t00010 > 0 ? "ON" : "OFF", null);
                        statusFragment.setValue(index, TextTools.byteToHexString(bytes), null);
                        settingFragment.setValue(index, String.valueOf(a), null,t00010);
                    }else if(index==40031){
                        systempw=TextTools.byteToHexString(bytes);
                    }else if(index==40030){
                        userpw=TextTools.byteToHexString(bytes);
                    }
                    index++;
                }

            }
            if (GlobalIndex == 1) {
                List<Float> points = new ArrayList<>();
                for (byte unsignedByte : bydata) {
                    int i = TextTools.byteToInt1(unsignedByte);
                    points.add((float) i);
                }
                    waveFormFragment.add41001(points,true);
            }else  if (GlobalIndex==2) {
                List<Float> points = new ArrayList<>();
                for (byte unsignedByte : bydata) {
                    int i = TextTools.byteToInt1(unsignedByte);
                    points.add((float) i);
                }
                    waveFormFragment.add42001(points,true);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void settinghandle(byte[] data) {
        String s = TextTools.byteToHexString(data);
        if(s.equals(scmd)){
            ToastUtil.showShort(this,"设置成功");
        }else{
            //ToastUtil.showShort(this,"设置失败");
        }
        Log.e(TAG, "settinghandle: " + s);
    }

    String cache = "";

    Timer timerJsd = null;
    BleNotifyResponse bleNotifyResponse = new BleNotifyResponse() {
        @Override
        public void onNotify(UUID service, UUID character, final byte[] value) {
            //hexString2Bytes()将16进制字符串转化为byte数组
            cache += TextTools.byteToHexString(value);
            android.util.Log.i(TAG, "cache: " + cache);
            if (timerJsd != null) {
                timerJsd.cancel();
                timerJsd = null;
            }
            //定时器
            timerJsd = new Timer();
            timerJsd.schedule(new TimerTask() {
                @Override
                public void run() {
                    BleDetailActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handle(TextTools.hexString2Bytes(cache));
                            cache = "";
                            timerJsd = null;
                        }
                    });
                }
            }, 100);//延时1s
        }

        @Override
        public void onResponse(int code) {
            Log.e(TAG, "notify onResponse: " + code);
            if (code == REQUEST_SUCCESS) {

            }
        }
    };


    int requstCode = 99;
    BleConnectStatusListener bleConnectStatusListener = new BleConnectStatusListener() {
        @Override
        public void onConnectStatusChanged(String mac, int status) {
            dismisspg();
            if (status == Constants.STATUS_CONNECTED) {


            } else if (status == Constants.STATUS_DISCONNECTED) {
                Toast.makeText(BleDetailActivity.this, "连接断开", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.getBle().unnotify(mac, serviceUUID, readUUID, new BleUnnotifyResponse() {
            @Override
            public void onResponse(int code) {
                Log.e(TAG, "onResponse: code  " + code);
            }
        });

        App.getBle().unregisterConnectStatusListener(mac, bleConnectStatusListener);
        if (timer != null) {
            timer.cancel();
        }
    }

    private void sendCmd(String cmd) {
        App.getBle().write(mac, serviceUUID, sendUUID, TextTools.hexString2Bytes(cmd), new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                Log.e(TAG, "write onResponse: " + code);
                if (code == REQUEST_SUCCESS) {

                }
            }
        });
    }
    String scmd="";
    public void sendCmd(byte[] cmd) {
        scmd= TextTools.byteToHexString(cmd);

        statusFragment.addMsg(scmd);

        timeStamp = System.currentTimeMillis();
        App.getBle().write(mac, serviceUUID, sendUUID, cmd, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                Log.e(TAG, "write onResponse: " + code);
                if (code == REQUEST_SUCCESS) {

                }
            }
        });
    }

    public void sendSettingCmd(byte[] cmd) {
        timeStamp = System.currentTimeMillis();
        App.getBle().write(mac, serviceUUID, sendUUID, cmd, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                Log.e(TAG, "write onResponse: " + code);
                if (code == REQUEST_SUCCESS) {

                }
            }
        });
    }


    private long timeStamp = 0;
    private List<Integer> list = new ArrayList<>();
    Timer timer;

    private void initDictionaries() {
        list.add(0001);
        list.add(1001);
        list.add(2001);

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    if ((System.currentTimeMillis() - timeStamp) > 760) {
                        if (indexfalg == 0||indexfalg == 2) {
                            nextRead();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1600, 800);
    }

    int GlobalIndex = 0;
    Integer integer;

    private void nextRead() {
        GlobalIndex++;
        if (GlobalIndex >= list.size()) {
            GlobalIndex = 0;
        }
        try {
            integer = list.get(GlobalIndex);
            Log.e(TAG, "nextRead: " + integer);
            byte[] date = CmdUtlis.grtCmdSetting( (byte) 3, integer, GlobalIndex == 0 ? 50:125, new byte[]{});
            sendCmd(date);
           // handle(TextTools.hexString2Bytes("0103FA00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000AE5000"));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                exit();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


}
